 <template>

  <div id="Catalog">
    <div id="Cart">

      <favorite></favorite>

      <br>
      <br>
      <h2>购物车</h2>
      <br>
      <br>
      <input type="submit" value="更新购物车" v-if="cartList.length" @click="getData">
      <form @submit.prevent="submitForm">

<!--        要判断购物车里有没有东西-->
        <table class="table_1" id="CPI" align="center" v-if="cartList.length" >

          <tr>
            <th></th>
            <th><b>商品</b></th>
            <th><b>商品编号</b></th>
            <th><b>商品门类编号</b></th>
            <th><b>详情</b></th>
            <th><b>是否有库存</b></th>
            <th><b>数量</b></th>
            <th><b>单价</b></th>
            <th><b>总价</b></th>
            <th>&nbsp;</th>
          </tr>

          <tr v-for="(cartItem, index) in cartList" :key="index">

            <td><input class="cart_pic_td" type="checkbox" v-model="cartItem.selected" @change="updateCartSubtotal"></td>

            <td class="cart_pic_td"><img :src=getImageUrl(cartItem.description) class="cart_pic" /></td>

            <td>
              <a class="itemId" >{{cartItem.itemId}}</a>
            </td>

            <td>
                {{cartItem.productId}}
            </td>

            <td>
              {{ cartItem.productName }}
            </td>

            <td>
              {{cartItem.inStock}}
            </td>

            <td>
              <input type="number" class="quantity" v-model="cartItem.quantity" @change="updateTotal(cartItem)">
            </td>

            <td>
              <label class="cartItemsPrice" ></label>
              {{cartItem.listPrice}}
            </td>

            <td class="total">
              <label class="cartItemsTotalPrice" ></label>
              <!--                                <fmt:formatNumber value="${cartItem.total}" pattern="$#,##0.00"/>-->
              {{cartItem.total}}
            </td>

            <td>
              <!--  传一个workingItemId过去，routerlink带参数-->
              <a id="delete" class="Button" @click="deleteItem(cartItem,index)">删除</a>
            </td>
          </tr>

          <tr>
            <td>
              总价
            </td>
            <td colspan="9"><label id="subtotal">{{ total }}</label></td>

          </tr>
          <!--                     这里两个if语句是对应两种情况，在刚进入页面时，numberofitems是空，在清空购物车后则是0，我也不知道为啥-->
        </table>
        <!--    购物车为空的时候显示，暂时先不用    -->
        <table id="CPI" align="center" v-if="!cartList.length">
          <tr>
            <td colspan="10"><b>你的购物车是空的，去下单试试吧！</b></td>
          </tr>
        </table>
      </form>
      <br>
      <br>
      <!--      跳到支付页面，要判断，如果cart有东西才显示-->
      <a class="Button" type="submit" v-if="cartList.length" @click="submitForm" >支付</a>
      <br>
      <br>
    </div>
    <div id="Separator"></div>
  </div>

  <div>
    <br>
    <br>
    <!--    放recommend-->
    <recommend></recommend>
  </div>

</template>


<script>
import {reactive, ref, computed,onMounted} from 'vue'
import router from '../../router'
import api from "../../api/index";
import axios from "axios";

export default {
  name: "CartView",
  setup(){
    //TODO 记得从session拿到username，下面的都是这个username

    const user = JSON.parse(sessionStorage.getItem('user'))
    let user_name = ''
    if(user){
      user_name = user.username

    }

    const cartList = reactive([
      //{itemId:'EST-12',description:'../../assets/images/forzenMUSI.jpg',productId:'CHEESE-02',productName:'冻慕斯与芝士',inStock:'true',quantity:'1',listPrice:'18.50',total:'18.50'}

    ]);

    let isCart = ref(false)
    //获取函数 TODO 获取真数据之后记得取消掉注释
    onMounted(() => {
      getData()
    })

    //初始得到数据
    const getData = () => {

      //TODO 记得从session拿到username，下面的都是这个username

        if(user_name!=''){

          api.getCartListByName(user_name).then(res => {

            cartList.splice(0,cartList.length)
            cartList.push(...res.data.data)

            const cartNum = cartList.length
            sessionStorage.setItem('cart_num',cartNum.toString())


          })
        }

    }

    const getImageUrl = (url) => {
      return new URL(url, import.meta.url).href;
    };

    //计算购物车总价
    const total = ref(0);

    //这是原来没有复选框的时候用的
    // const total = computed(() => {
    //     let sum = 0;
    //     for(let i = 0;i < cartList.length; i++){
    //       sum += cartList[i].total;
    //     }
    //
    //     return sum;
    // });

    //根据购物车选择的商品计算总价，没勾选的话总价就是0
    function updateCartSubtotal(){
      this.total = cartList
          .filter(item => item.selected)
          .reduce((acc, curr) =>  acc + (curr.listPrice * curr.quantity), 0);
    }

    //购物车数目更新
    function updateTotal(cartItem){
      // for (let i = 0; i < cartList.length; i++) {
      //   cartList[i].total = cartList[i].quantity * cartList[i].listPrice;
      // }

      cartItem.total = cartItem.quantity * cartItem.listPrice;
      //console.log(cartItem.itemId + cartItem.quantity+'修改数量')

      let formData = new FormData();
      formData.append('username', user_name);
      formData.append('itemId', cartItem.itemId);
      formData.append('quantity',cartItem.quantity)

      api.updateQuantityByItemId(formData)
          .then((res => {
            console.log("数据库更新成功");
          })
          // .catch((error) => {
          //   console.log(error);
          // })
          )
    };

    //删除某一项
    function deleteItem(cartItem,index){
        //console.log(cartItem.itemId+'删除物品')
      let delete_form = new FormData();
      delete_form.append('username', user_name);
      delete_form.append('itemId', cartItem.itemId);
       api.deleteCartItem(delete_form)
           .then((res =>{
             console.log(res.message)
           }))

      //删除后更新界面视图
      console.log(index);
      cartList.splice(index, 1);
    }

    //之后这里从session里拿
    const account = user

    //     {
    //   "username": "j2ee",
    //   "email": "yourname@yourdomain.com",
    //   "firstName": "ABC",
    //   "lastName": "XYX",
    //   "status": null,
    //   "address1": "901 San Antonio Road",
    //   "address2": "MS UCUP02-206",
    //   "city": "Palo Alto",
    //   "state": "CA",
    //   "zip": "94303",
    //   "country": "USA",
    //   "phone": "15679315619",
    //   "signOn": {
    //     "username": "j2ee",
    //     "password": "e10adc3949ba59abbe56e057f20f883e"
    //   },
    //   "profile": {
    //     "username": "j2ee",
    //     "languagePreference": "English",
    //     "favouriteCategoryId": "CHEESS",
    //     "listOption": true,
    //     "bannerOption": true
    //   },
    //   "bannerData": {
    //     "favouriteCategoryId": "CHEESS",
    //     "bannerName": "<image <image src=\"../images/cats_icon.gif\"><font size=\"5\" color=\"blue\"> Cats</font>"
    //   }
    // }

    //跳转支付界面
    function submitForm() {
      const selectedItems = cartList.filter(item => item.selected)

      if(selectedItems.length<=0){
        alert("未选中任何商品!!  请选择商品后支付")
      }

      else{
        const payForm = {
          account:account,
          carts:selectedItems,

        };

        const jsonForm = JSON.stringify(payForm)

        api.cartToOrder(jsonForm)
            .then((res =>{
              console.log(res.data.msg)

              sessionStorage.setItem('orderDate',res.data.data.orderDate.toString())
              sessionStorage.setItem('order',JSON.stringify(res.data.data))

            }))


        //获取购物车全部总价
        sessionStorage.setItem('total', total.value.toString());
        router.push('/main/NewOrder');
      }
    }

    return {
      cartList,
      total,
      isCart,
      updateTotal,
      getImageUrl,
      submitForm,
      getData,
      deleteItem,
      updateCartSubtotal
    };
  },

  // data(){
  //   return{
  //     cartItems:[
  //       {itemId:'EST-12',description:'/static/images/forzenMUSI.jpg',productId:'CHEESE-02',productName:'冻慕斯与芝士',inStock:'true',quantity:'1',listPrice:'18.50'}
  //     ],
  //
  //   }
  // },
  //
  // computed: {
  //   calculatedCartItems() {
  //     return this.cartItems.map(item => ({
  //       ...item,
  //       total: item.listPrice * item.quantity
  //     }));
  //   }
  // },

}
</script>

<style scoped>
table {
    text-align: center;
    border-collapse:collapse;
}

td {
    padding: 20px 38px;
}

tr:nth-child(2n-1) td {
    background-color: rgba(222, 222, 222, 0.53);
}

tr:nth-child(2n) td {
    background-color: rgba(222, 222, 222, 0.72);
}
</style>